package middleware

import (
	"api/internal/types"
	"api/pkg"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type ValiMiddleware struct {
}

func NewValiMiddleware() *ValiMiddleware {
	return &ValiMiddleware{}
}

func (m *ValiMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		token := r.Header.Get("token")
		getToken, err := pkg.GetToken(token)
		if err != nil {
			httpx.OkJsonCtx(r.Context(), w, &types.Response{
				Code:    500,
				Message: err.Error(),
				Date:    nil,
			})
			return
		}
		if getToken["vali"].(string) != "1" {
			httpx.OkJsonCtx(r.Context(), w, &types.Response{
				Code:    500,
				Message: "账号未实名",
				Date:    nil,
			})
			return
		}
		r.ParseForm()
		r.Form.Set("userId", getToken["user"].(string))
		next(w, r)
	}
}
